package com.yc.login.web;

import com.yc.bean.Result;
import com.yc.biz.BizException;
import com.yc.login.bean.LoginProperties;
import com.yc.util.Utils;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("login")
public class LoginDo {
    @Autowired
    LoginProperties properties;
    @Autowired
    JdbcTemplate jdbcTemplate;
    @GetMapping("config")
    LoginProperties properties(){
        return properties;
    }
    @RequestMapping("login")
        public Result login(String username, String password, HttpSession session) throws BizException, ClassNotFoundException {
        Utils.checkEmpty(username,"请输入用户名");
        Utils.checkEmpty(password,"请输入密码");
        Utils.check(password.trim().length()<3,"密码至少是3个字符");
        String sql="select * from %s where %s=? and %s=?";
        sql=String.format(sql,properties.getUserTable(),
                properties.getUsernameColumn(),
                properties.getPasswordColumn());
        List list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(properties.getUserClassObject()),
                username, password);
        Utils.check(list.isEmpty(),"用户名密码错误");
        Utils.check(list.size()>1,"多个用户名相同");
        Object user = list.get(0);
        session.setAttribute(properties.getSessionKey(),user);

        //如果是被拦截后重登，跳转之前的页面
        Map<String,Object> map=new HashMap<>();
        map.put("user",user);
        Object aGoto = session.getAttribute("goto");
        if(aGoto!=null){
            map.put("goto",aGoto);
        }
        return new Result(1,"登录成功",map);
}
    @RequestMapping("myinfo")
    Result myinfo(@SessionAttribute(value = "loginedUser",required = false) Object myinfo) throws BizException {
//        Object myinfo = session.getAttribute(properties.getSessionKey());
        if(myinfo==null){
            throw new BizException("未登录");
        }
        return new Result(1, "已登录", myinfo);
    }

    @RequestMapping("logout")
    ModelAndView logout(ModelAndView modelAndView, HttpSession session) {
        session.invalidate();
        modelAndView.setViewName("redirect:/");
        return modelAndView;
    }
    @RequestMapping("getUsernameColumn")
    String getUsernameColumn(){
        return properties.getUsernameColumn();
    }

}

